<?php


namespace app\common\model;

use app\common\model\Common as CommonModel;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Cookie;


class Users extends CommonModel
{
    protected $pk = 'id';

    /**
     * index页面数据获取
     * */
    public function tableData($post,$field='*',$isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = 10;
        }

        $tableWhere = $this->tableWhere($post);
        $query      = $this
            ->field($field)
            ->where($tableWhere['where'])->whereOr($tableWhere['whereOr'])->order($tableWhere['order']);


        if ($isPage) {
            $list        = $query->paginate([
                'list_rows'=> $limit,//每页数量
                'query' => request()->param(),
            ]);
            $data        = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $page = $list->render();
            $re['count'] = $list->total();
        } else {
            $list        = $query->select();
            $data        = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
            $page = [];
        }

        $re['code'] = 1;
        $re['msg']  = '';
        $re['data'] = $data;
        $re['page'] = $page;
        return $re;
    }


    protected function tableWhere($post)
    {
        $where = $whereOr = [];
        if(isset($post['name']) && !empty($post['name'])){
            $where[] = ['name','like','%'.$post['name'].'%'];
        }
        if(isset($post['mobile']) && !empty($post['mobile'])){
            $where[] = ['mobile','like','%'.$post['mobile'].'%'];
        }

        if(isset($post['status']) && $post['status'] != ''){
            $where[] = ['status','=',$post['status']];
        }
        if(isset($post['is_vip']) && $post['is_vip'] != ''){
            $where[] = ['is_vip','=',$post['is_vip']];
        }

        /*
        if(isset($post['class_name']) && !empty($post['class_name'])){
            $where[] = ['class_name','=',$post['class_name']];
        }
        if(isset($post['keywords']) && !empty($post['keywords'])){
            $where[] = ['name','like','%'.$post['keywords'].'%'];
        }*/

        $result['where']   = $where;
        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $pk = $this->pk;
        $result['order'] = [$pk => 'desc'];
        return $result;
    }

    protected function tableFormat($list)
    {
        $users_status = config("app.users_status");
        foreach($list as $k=>$v){
            $list[$k]['add_time'] = date('Y-m-d',$v['add_time']);
            $list[$k]['status_name'] = $users_status[$v['status']];
            $list[$k]['type_name'] = $v['type'] ==1 ?"房东":"租客";
//            $list[$k]['is_vip_name'] = $users_status[$v['is_vip']];
        }
        return $list;
    }


    public function handle($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $act = $param['act'];

        if(!empty($param['head_pic'])){
            if(is_array($param['head_pic'])){
                $data['head_pic'] = implode(',',$param['head_pic']);
            }else{
                $data['head_pic'] = $param['head_pic'];
            }
        }
        //$data['username'] = isset($param['username'])?$param['username']:'';
        $data['mobile'] = isset($param['mobile'])?$param['mobile']:'';
        $data['sex'] = isset($param['sex'])?$param['sex']:'';
        $data['card_num'] = isset($param['card_num'])?$param['card_num']:'';
//        $data['unit'] = isset($param['unit'])?$param['unit']:'';
        //$data['address'] = isset($param['address'])?$param['address']:'';
        $data['openid'] = isset($param['openid'])?$param['openid']:'';
        $data['unionid'] = isset($param['unionid'])?$param['unionid']:'';
        $data['type'] = isset($param['type'])?$param['type']:1;
        $data['people_id'] = isset($param['people_id'])?$param['people_id']:'';

        $data['sex'] = isset($param['sex'])?$param['sex']:'';
        $data['card_num'] = isset($param['card_num'])?$param['card_num']:'';
        $data['card_address'] = isset($param['card_address'])?$param['card_address']:'';
        $data['unit_name'] = isset($param['unit_name'])?$param['unit_name']:'';
        $data['unit_position'] = isset($param['unit_position'])?$param['unit_position']:'';
        $data['picurl'] = isset($param['picurl'])?$param['picurl']:'';

//        $data['contacts'] = isset($param['contacts'])?$param['contacts']:'';
//        $data['contacts_mobile'] = isset($param['contacts_mobile'])?$param['contacts_mobile']:'';
//
//        $data['province_id'] = isset($param['province_id'])?$param['province_id']:'';
//        $data['province'] = isset($param['province'])?$param['province']:'';
//        $data['city_id'] = isset($param['city_id'])?$param['city_id']:'';
//        $data['city'] = isset($param['city'])?$param['city']:'';
//        $data['area_id'] = isset($param['area_id'])?$param['area_id']:'';
//        $data['area'] = isset($param['area'])?$param['area']:'';
        //$data['status'] = isset($param['status'])?$param['status']:0;
        if(isset($param['status'])){
            $data['status'] = $param['status'];
        }

        if($act == 'add' || $act == 'register'){
            $data['name'] = isset($param['name'])?$param['name']:$param['mobile'];
            //$data['token'] = $this->create_token();
            $data['sort'] = $this ->max('sort') + 1;
            $data['password'] = !empty($param['password'])?md5(md5($param['password'])):md5(md5('123456'));
            $data['add_time'] = time();
            $r = $this->insertGetId($data);
            $id = $r;
        }
        if($act == 'edit'){
            $data['name'] = isset($param['name'])?$param['name']:'';
            if(!empty($param['password'])){
                $data['password'] = md5(md5($param['password']));
            }
            $data['update_time'] = time();
            $r = $this->where('id','=',$param['id'])->update($data);
            $id = $param['id'];
        }
        if(!$r){
            $result['msg'] = '操作失败';
            return $result;
        }
        $result['code'] = 1;
        $result['msg'] = '操作成功';
        $result['data'] = $id;
        return $result;
    }


    /*//生成token(废弃)
    public function create_token(){
        return md5(time().mt_rand(1,999999999));
    }*/

    //小程序user_id登录
    public function wxLogin($user_id){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $info = $this->where('id','=',$user_id)->find();
        if(!$info['id']){
            $result['msg'] = '没有此用户';
            return $result;
        }
        if($info['is_open'] != 1){
            $result['msg'] = '当前用户已被关闭，请联系管理员';
            return $result;
        }

        $data['user_id'] = $info['id'];
        $data['name'] = $info['name'];
        $data['mobile'] = $info['mobile'];
        $data['sex'] = $info['sex'];
        $data['head_pic'] = $info['head_pic'];
        $data['status'] = $info['status'];
        $data_json = json_encode($data);
        $data['token'] = signToken($data_json);

        Cookie::set('token', $data['token'], 43200);
        \think\facade\Cookie::save();

        $result['code'] = 1;
        $result['msg'] = '登录成功';
        $result['data'] = $data;
        return $result;

    }


    //登录
    public function login($mobile,$password='',$type=2){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $info = $this->where([
            'mobile'=>$mobile,
            'type'=>$type
        ])->find();
        if(!$info['id']){
            $result['msg'] = '没有此用户';
            return $result;
        }

        if($info['is_open'] != 1){
            $result['msg'] = '当前用户已被关闭，请联系管理员';
            return $result;
        }
        if($password) {
            if (md5(md5($password)) != $info['password']) {
                $result['msg'] = '密码不正确';
                return $result;
            }
        }

        $data = $this->setCacheAndToekn($info);

        $result['code'] = 1;
        $result['msg'] = '登录成功';
        $result['data'] = $data;
        return $result;
    }

    //设置缓存和token
    public function setCacheAndToekn($info){

        $data['user_id'] = $info['id'];
        $data['name'] = $info['name'];
        $data['mobile'] = $info['mobile'];
        $data['sex'] = $info['sex'];
        $data_json = json_encode($data);
        $token = signToken($data_json);
        $data['token'] = $token;

        /*Session::set('user_id', $info['id']);
        Session::set('name', $info['name']);
        Session::set('mobile', $info['mobile']);
        Session::set('token', $token);
        \think\facade\Session::save();*/

        Cookie::set('user_id', $info['id'], 43200);
        Cookie::set('name', $info['name'], 43200);
        Cookie::set('mobile', $info['mobile'], 43200);
        Cookie::set('token', $token, 43200);

        \think\facade\Cookie::save();

        return $data;
    }


    //第三方登录
    public function thirdLogin($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $unionid = $param['unionid'];

        $user_one = $this->where('unionid','=',$unionid)->where('is_open','=',1)->find();
        if(!$user_one){
            //没有此用户创建
            $data['name'] = $param['nickname'];
            $data['head_pic'] = $param['head_pic'];
            $data['password'] = md5(md5('123456'));
            $data['unionid'] = $param['unionid'];
            $data['add_time'] = time();
            $data['sort'] = $this ->max('sort') + 1;

            $id = $this->insertGetId($data);
            $info = $this->where("id",'=',$id)->find();
        }else{
            $info = $user_one;
        }

        $this->setCacheAndToekn($info);

        $result['code'] = 1;
        $result['msg'] = '登录成功';
        return $result;
    }


    //更换手机号
    public function update_mobile($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];

        $res = $this->where('mobile','=',$param['old_mobile'])->update([
            'mobile'=>$param['new_mobile']
        ]);
        if(!$res){
            $result['msg'] = '修改失败';
            return $result;
        }

        $result['code'] = 1;
        $result['msg'] = '修改成功';
        return $result;
    }

    //修改密码
    public function update_pwd($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $info = $this->where('mobile','=',$param['old_mobile'])->find();
        if(md5(md5($param['old_password'])) != $info['password']){
            $result['msg'] = '原密码不正确';
            return $result;
        }

        $res = $this->where('mobile','=',$param['old_mobile'])->update([
            'password'=>md5(md5($param['new_password']))
        ]);

        if(!$res){
            $result['msg'] = '修改失败';
            return $result;
        }
        $result['code'] = 1;
        $result['msg'] = '修改成功';
        return $result;
    }

    //修改密码（没有原密码）
    public function forgetpwd($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];

        $one = $this->where('mobile','=',$param['forget_mobile'])->find();
        if(!$one){
            $result['msg'] = '没有此用户';
            return $result;
        }
        if($param['password'] != $param['repassword']){
            $result['msg'] = '两次密码不一致';
            return $result;
        }

        $res = $this->where('mobile','=',$param['forget_mobile'])->update([
            'password'=>md5(md5($param['password']))
        ]);

        if(!$res){
            $result['msg'] = '修改失败';
            return $result;
        }
        $result['code'] = 1;
        $result['msg'] = '修改成功';
        return $result;
    }




}